package com.huawei.housekeeper.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huawei.housekeeper.dao.entity.ServiceImage;
import com.huawei.housekeeper.dao.mapper.ServiceImageMapper;
import com.huawei.housekeeper.exception.Assert;
import com.huawei.housekeeper.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.tika.Tika;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import static com.huawei.housekeeper.enums.ErrorCode.*;
import static org.springframework.http.MediaType.IMAGE_JPEG_VALUE;
import static org.springframework.http.MediaType.IMAGE_PNG_VALUE;

@RestController
@RequestMapping("/housekeeper")
@Api(tags = "图片接口")
@Slf4j
public class ImageServiceController {


    @Autowired
    private ServiceImageMapper serviceImageMapper;

    @PostMapping(value = "/image/upload")
    @ApiOperation(value = "上传图片")
    public @ResponseBody Result<String> uploadImage(@ApiParam(name = "file", value = "图片", required = true) @RequestPart("file") MultipartFile multipartFile) {
        log.info("文件上传开始，{}", multipartFile.getOriginalFilename());
        String fileName = "";
        Tika tika = new Tika();
        if (!multipartFile.isEmpty()) {
            try {
                String miniType = tika.detect(multipartFile.getInputStream());
                Assert.isTrue((miniType.equals(IMAGE_PNG_VALUE) || miniType.equals(IMAGE_JPEG_VALUE)), UPLOAD_FILE_TYPE_ERROR.getMessage());

                fileName = UUID.randomUUID().toString();
                String type = multipartFile.getContentType();
                assert type != null;
                ServiceImage serviceImage = new ServiceImage();
                serviceImage.setImageName(multipartFile.getOriginalFilename());
                serviceImage.setImgSrc(fileName);
                serviceImage.setContent(multipartFile.getBytes());
                serviceImage.setType(type);
                serviceImageMapper.insert(serviceImage);
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
                return Result.createResult(SERVER_ERROR.getCode(), SERVER_ERROR.getMessage());
            }
        } else {
            return Result.createResult(fileName);
        }
        return Result.createResult(fileName);
    }

    @GetMapping("/image")
    @ApiOperation(value = "查看图片")
    @ResponseBody
    public ResponseEntity<byte[]> getImageByName(@ApiParam(name = "name", value = "图片名称,例: 676987979.jpg", required = true) @RequestParam("name") String name) {
        LambdaQueryWrapper<ServiceImage> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(ServiceImage::getImgSrc, name);
        List<ServiceImage> list = serviceImageMapper.selectList(queryWrapper);
        Assert.isTrue(!list.isEmpty(), QUERY_RESULT_EMPTY.getMessage());
        ServiceImage serviceImage = list.get(0);
        String type = serviceImage.getType().substring(serviceImage.getType().lastIndexOf("/") + 1);
        MediaType contentType = type.equals(MediaType.IMAGE_JPEG.getType())?MediaType.IMAGE_JPEG : MediaType.IMAGE_PNG;
        return ResponseEntity.ok().contentType(contentType).body(serviceImage.getContent());
    }
}
